// miniprogram/pages/admin/gallary/gallary.js
const app = getApp();
const MAX_IMAGE_SIZE = 8 * 1024 * 1024 * 1024;
const uploader = require('../../utils/upload.js');
const util = require("../../utils/util.js");
Page({

  isEnd: false,
  images: [],
  /**
   * 页面的初始数据
   */
  data: {
    items: [],
    count: 9,
    selectedItems: [] // 仅用于排除已选择列表
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this;
    const eventChannel = this.getOpenerEventChannel();
    eventChannel.on('setImages', function (res) {
      if (res.count) {
        that.setData({ count: res.count });
      }
      if (res.items) {
        let selectedItems = [];
        res.items.map(v => {
          selectedItems.push(v.src);
        })
        that.setData({ selectedItems });
      }
    })
    app.login(user => {
      if (!user.studioid) {
        //   wx.navigateBack();
        //   return;
        user.studioid = user.openid;
      }
      this.setData({ studioid: user.studioid });
      this.loadItems(true);
    });

  },

  loadItems(reload) {
    let items = this.data.items;
    if (!reload && this.isEnd) return;

    wx.cloud.callFunction({
      name: 'crud',
      data: {
        op: 'get',
        table: 'gallary',
        skip: reload ? 0 : items.length,
        where: { studioid: app.globalData.user.studioid }
      },
      success: res => {
        this.isEnd = res.result.data < 20;
        if (reload) {
          items = [];

        }
        items = items.concat(res.result.data.filter(v => {
          return this.data.selectedItems.indexOf(v.src) < 0
        }));
        this.images = [];
        items.map((v, i) => {
          this.images.push(v.src.replace(/\/mini$/i, ''))
          //this.images.push(v.src.substring(0,v.src.length-5))
        })
        //   console.log(this.images)
        this.setData({ items });
      }
    })
  },

  chooseImg: function (e) {
    const that = this;
    // const id = e.currentTarget.dataset.id;
    wx.chooseImage({
      sizeType: ['original'],
      count: 9,
      success: res => {
        res.tempFiles.map((tempFile, index) => {
          if (tempFile.size > MAX_IMAGE_SIZE) {
            wx.showToast({
              title: '图片过大，请重新选择',
              icon: 'none'
            })
            return;
          }
          // TODO 如果文件较大，自动启用压缩
          wx.getImageInfo({
            src: tempFile.path,
            success: r => {
              let logo = {
                src: tempFile.path,
                size: tempFile.size,
                width: r.width / r.height,
                // uploaded: false
              }
              that.uploadImage(logo);
            }
          })
        });
      },
      fail: e => {
        wx.hideLoading();
      }
    })
  },

  // uploadImage_cos: function (node) {
  //   return new Promise((resolve, reject) => {
  //     wx.showLoading({
  //       title: '正在上传...',
  //       icon: 'none'
  //     });
  //     let fn = Date.now().toString(36) + Math.random().toString(36).substr(2) + node.src.match(/\.[^.]+?$/)[0];
  //     let options = {
  //       bucket: 'p-1301301505', // TODO 需要替换为当前用户对应的存储桶
  //       cloudPath: `${app.globalData.user.openid}/gallary/${fn}`, // TODO 需要替换这当前用户对应的路径
  //       filePath: node.src,
  //       success: res => {
  //         console.log(res);
  //         node.src = res.fileID + '/mini';
  //         wx.cloud.callFunction({
  //           name: 'crud',
  //           data: {
  //             op: 'add',
  //             table: 'gallary',
  //             data: {
  //               studioid: this.data.studioid,
  //               src: node.src,
  //               size: node.size,
  //               width: node.width
  //             }
  //           },
  //           success: result => {
  //             wx.hideLoading();
  //             console.log(result);
  //             node._id = result.result._id;

  //             let items = this.data.items;
  //             if (items.filter(v => { return v.selected === true }).length < this.data.count) {
  //               node.selected = true;
  //             }
  //             items.unshift(node);

  //             this.setData({ items });
  //           }
  //         })
  //         // node.uploaded = true;
  //         resolve(node)
  //       },
  //       fail: err => {
  //         reject(err)
  //       }
  //     }
  //     uploader.uploadFile(options);
  //   })
  // },
  uploadImage: function (node) {
    let that = this
    return new Promise((resolve, reject) => {
      wx.showLoading({
        title: '正在上传...',
        icon: 'none'
      });
      let fn = Date.now().toString(36) + Math.random().toString(36).substr(2) + node.src.match(/\.[^.]+?$/)[0];

      wx.cloud.uploadFile({
        cloudPath: `userAsset/${app.globalData.user.openid}/gallary/${fn}`,
        filePath: node.src,
        success(res) {
          console.log('上传', res)
          wx.cloud.getTempFileURL({
            fileList: [res.fileID],
            success(res) {
              console.log('获取http地址', res);
              node.src = res.fileList[0].tempFileURL;
              node.fileID = res.fileList[0].fileID
              console.log(node)
              wx.cloud.callFunction({
                name: 'crud',
                data: {
                  op: 'add',
                  table: 'gallary',
                  data: {
                    studioid: that.data.studioid,
                    src: node.src,
                    size: node.size,
                    width: node.width
                  }
                },
                success: result => {
                  wx.hideLoading();
                  console.log(result);
                  node._id = result.result._id;

                  let items = that.data.items;
                  if (items.filter(v => { return v.selected === true }).length < that.data.count) {
                    node.selected = true;
                  }
                  items.unshift(node);

                  that.setData({ items });
                }
              })
              resolve(node)

            },
            fail: err => {
              reject(err)
            }
          })

        },
        fail: err => {
          reject(err)
        }
      })

    })
  },
  selectImg(e) {
    let index = e.currentTarget.dataset.index;
    let selected = !!e.currentTarget.dataset.selected;

    if (!selected && this.data.count === 1) {
      let lastIndex = this.data.items.findIndex(v => { return v.selected == true });
      if (lastIndex >= 0) {
        this.setData({ [`items[${lastIndex}].selected`]: false });
      }
      this.setData({ [`items[${index}].selected`]: true });
      return;
    }

    let selecteditems = this.data.items.filter(v => { return !!v.selected });
    if (selected && selecteditems.length >= this.data.count) return;
    this.setData({ [`items[${index}].selected`]: !selected });
  },

  previewImg(e) {

    wx.previewImage({
      urls: this.images,
      current: this.images[0]
    })
  },

  back(e) {
    wx.navigateBack();
  },

  submit(e) {
    let items = this.data.items;
    let selected = [];
    items.map(v => {
      if (v.selected) {
        selected.push({ src: v.src, _id: v._id, width: v.width });
      }
    })
    // let selected = items.filter(v=>{return !!v.selected});

    if (selected.length > 0) {
      this.getOpenerEventChannel().emit('setImages', selected);
      wx.navigateBack();
    } else {
      wx.showToast({
        title: '请选择至少一张图片',
        icon: 'none'
      })
    }
  },

  showActions(e) {
    let index = e.currentTarget.dataset.index;
    let items = this.data.items;
    let node = items[index]
    const that = this;
    wx.showActionSheet({
      itemList: ['删除'],
      success(res) {
        switch (res.tapIndex) {
          case 0:
            wx.showModal({
              content: '如果图片已被使用，将不能再显示。您确定要删除吗？',
              showCancel: true,
              success: rr => {
                console.log(node)
            
                if (!node.fileID) {
                  uploader.deleteFiles({
                    bucket: 'p-1301301505',
                    files: [node.src.substr(0,node.src.length-5)],
                    success: r => {
                      console.log("Remove images success", r, that.removeImages)

                    },
                    fail: err => {
                      console.error("Remove images fail", err, that.removeImages)
                    }
                  });
                } else {
                  wx.cloud.deleteFile({
                    fileList: [node.fileID], success: res => {
                      console.log('从云存储中删除', res);

                    }
                  });
                }

                //删除数据库中记录
                wx.cloud.callFunction({
                  name: 'crud',
                  data: {
                    op: 'remove',
                    table: 'gallary',
                    _id: items[index]._id,
                  },
                  success: result => {
                    console.log(result);
                    if (result.result.stats.removed === 1) {
                      items.splice(index, 1);
                      that.setData({ items });
                    }
                  }

                })




              },
              fail: e => {

              }
            })
        }
        console.log(res.tapIndex)
      },
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.loadItems(true);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.loadItems(false)
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})